import { ref, nextTick, onMounted, onUnmounted, toValue } from "vue";

const { VITE_SERVE_API_URL_WS: wsBaseUrl = "" } = import.meta.env;

/**
 * @description:   Websocket
 * @param {string} url
 * @param {function} cb   成功的回调
 * @param {function} cb2   失败的回调
 * @return {*}
 */
export class UseCommonWebSocket extends WebSocket {
  public url: string;
  public cb?: (data: any) => any;
  public cb2?: (data: any) => any;
  constructor(url: string, cb?: (data: any) => any, cb2?: (data: any) => any) {
    const facCode = localStorage.getItem("facCode");
    const realUrl = `${wsBaseUrl}${url}/${facCode}`;
    super(realUrl);
    this.url = realUrl;
    this.cb = cb;
    this.cb2 = cb2;

    this.onopen = ({ target: { url } }: any) => {
      const msg = `websocket（${url}）连接成功！！！`;
      console.log(msg);
    };
    this.onmessage = ({ data = "" }: any) => {
      this.cb && this.cb(data);
    };
    this.onclose = ({ reason }: any) => {
      const msg = `websocket（${url}）连接已断开：${reason}`;
      console.log(msg);
    };
    this.onerror = (err?: any) => {
      const msg = "websocket连接出错 ！！！";
      console.error(msg);
      this.cb2 && this.cb2(err);
    };
  }
}

/**
 * @description:   开启websocket监控  fab机台列表
 * @param {string} type
 * @param {string} className
 * @param {function} cb   onMounted回调
 * @param {function} cb2  onUnmounted回调
 * @return {*}
 */
export function useFabListSocket(type: string = "", className: string | (() => string) = "WATER", cb?: (data: any) => any, cb2?: () => any) {
  let ws = ref<any>(null);
  onMounted(async () => {
    await nextTick();
    const wsUrl = `/fabWs/fabWs/${type}/${toValue(className)}`;
    ws.value = new UseCommonWebSocket(wsUrl, data => {
      cb && cb(data);
    });
  });
  onUnmounted(() => {
    ws.value && ws.value?.close();
    cb2 && cb2();
  });
}

/**
 * @description:   开启websocket监控  fab机台详情
 * @param {boolean} active 是否激活websocket
 * @param {string} type
 * @param {string} eqpId
 * @param {function} cb
 * @return {*}
 */
export function useFabDetailSocket(active = false, type: string = "", eqpId: string = "", cb?: (data: any) => any) {
  let ws = null;
  const init = () => {
    const wsUrl = `/fabWs/fabWs/${type}/${eqpId}`;
    ws = new UseCommonWebSocket(wsUrl, data => {
      cb && cb(data);
    });
  };
  onMounted(() => {
    active && init();
  });
  onUnmounted(() => {
    active && ws && ws?.close();
  });
}
